import React, { useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { getRoomCanJoin } from '@/api/index'
import { connect } from 'react-redux'
import { joinRoom } from '@/utils/wss'
import { getLocalPreview } from '@/utils/webRtc'
import { setRoomInfo } from '@/store/actions'
import { useEffectOnce } from '@/utils/hooks'

import Users from './components/Users'
import MainView from './components/MainView'
import Control from './components/Control'

import './index.scss'

const VideoRoom = ({
  roomInfo,
  userId,
  setRoomInfoAction
}) => {
  const navigate = useNavigate()
  const { roomId } = useParams()
  const [selectUserId, setSelectUserId] = useState()
  const [showUsers, setShowUsers] = useState(true)

  /**
   * 初始化加入房间
   */
  const initData = async() => {
    /* 获取房间数据并赋值全局 */
    try {
      const res = await getRoomCanJoin(roomId)

      setRoomInfoAction(res.data)
    } catch (err) {
      alert('房间不可用')
      navigate('/join-room/Host', { replace: true })
    }

    /* 需要先获取本地媒体流，否则建立webRTC时媒体流会为空 */
    await getLocalPreview()

    joinRoom(userId, roomId)
  }

  /**
   * 点击不同的user框，将主视框切换成对应的用户内容
   * @param {String} userId
   */
  const onSelectUserId = (userId) => {
    if (userId === selectUserId) {
      return
    }
    setSelectUserId(userId)
    /* 把user的html映射给mainview */
    const userDOM = document.querySelector(`#user-view-${ userId }`)
    const mainDOM = document.querySelector('#main-view')

    if (!userDOM || !mainDOM) {
      return
    }
    mainDOM.innerHTML = userDOM.innerHTML

    /* 如果mainDOM有video标签，则需要把媒体流赋值给video */
    const mainVideo = mainDOM.querySelector('video')
    const userVideo = userDOM.querySelector('video')

    if (mainVideo && userVideo) {
      mainVideo.srcObject = userVideo.srcObject
      mainVideo.muted = true
    }
  }

  useEffectOnce(() => {
    initData()
    return () => {
      console.log(111111111)
    }
  })

  return roomInfo && roomInfo.users.length > 0 && (
    <div className="video-room">
      <MainView />
      <div className={showUsers ? '' : 'users-hidden'}>
        <Users
          onSelectUserId={onSelectUserId}
          roomInfo={roomInfo}
          selectUserId={selectUserId}
          userId={userId}
        />
      </div>

      <Control
        roomInfo={roomInfo}
        setShowUsers={setShowUsers}
        showUsers={showUsers} />
    </div>
  )
}

const mapStateToProps = (state) => ({ ...state })
const mapActionsToProps = (dispatch) => {
  return {
    setRoomInfoAction: (roomInfo) => dispatch(setRoomInfo(roomInfo)),
  }
}

export default connect(mapStateToProps, mapActionsToProps)(VideoRoom)
